import 'dart:async';

import 'package:chatgreat/helper/helper.dart';
import 'package:chatgreat/lang/lang.dart';
import 'package:chatgreat/page/component/background_container.dart';
import 'package:chatgreat/page/component/loading.dart';
import 'package:chatgreat/page/component/sliver_component.dart';
import 'package:chatgreat/page/creative_island/gallery/components/image_card.dart';
import 'package:chatgreat/page/creative_island/gallery/data/gallery_datasource.dart';
import 'package:chatgreat/page/component/theme/custom_size.dart';
import 'package:chatgreat/page/component/theme/custom_theme.dart';
import 'package:chatgreat/repo/api/creative.dart';
import 'package:chatgreat/repo/settings_repo.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_localization/flutter_localization.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:loading_more_list/loading_more_list.dart';

import '../../../helper/AppUtil.dart';
import '../../../helper/event.dart';
import '../../../repo/api_server.dart';
import '../../component/dialog.dart';

class GalleryScreen extends StatefulWidget {
  final SettingRepository setting;
  final int index;
  final bool enableDelete;
  const GalleryScreen({super.key, required this.setting, required this.index, this.enableDelete = false});

  @override
  State<GalleryScreen> createState() => _GalleryScreenState();
}

class _GalleryScreenState extends State<GalleryScreen> {
  final GalleryDatasource datasource = GalleryDatasource();
  Timer? _timer;

  @override
  void initState() {
    datasource.index = widget.index;
    GlobalEvent().on("refresh_gallery", (data) {
      print('-------------- > refresh_gallery');
      if (mounted) {
        datasource.refresh();
      }
    });
    super.initState();

    if (widget.index == 2) {
      _timer = Timer.periodic(const Duration(seconds: 5), (timer) {
        if (datasource.hasCreating) {
          datasource.refresh();
        }
      });
    }
  }

  @override
  void dispose() {
    if (_timer != null) {
      _timer!.cancel();
      _timer = null;
    }
    datasource.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final customColors = Theme.of(context).extension<CustomColors>()!;
    return BackgroundContainer(
      enabled: false,
      setting: widget.setting,
      child: Scaffold(
        backgroundColor: Colors.transparent,
        body: _buildIslandItems(customColors),
      ),
    );
  }

  /// 大家绘画列表
  Widget _buildIslandItems(
    CustomColors customColors,
  ) {
    return SliverCreateComponent(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const SizedBox(
            height: 12,
          ),
          Expanded(
            child: RefreshIndicator(
              displacement: 20,
              color: customColors.themeBlueColor,
              onRefresh: () {
                return datasource.refresh();
              },
              child: LoadingMoreList(
                ListConfig<CreativeGallery>(
                  shrinkWrap: true,
                  itemBuilder: (context, item, index) {
                    return ImageCard(
                      enableDelete: widget.enableDelete,
                      image: item.preview,
                      username: item.content,
                      userId: item.id,
                      likeNum: item.likeNum,
                      onTap: () {
                        if (isBlank(item.url ?? '')) return;
                        item.index = widget.index;
                        context.push('/creative-draw/gallery/${item.id}', extra: item);
                      },
                      onDeleteTap: () {
                        onItemDelete(
                          context,
                          item,
                          index,
                        );
                      },
                    );
                  },
                  sourceList: datasource,
                  padding: const EdgeInsets.only(
                      top: 16, left: 15, right: 15, bottom: 15),
                  extendedListDelegate: SliverWaterfallFlowDelegateWithFixedCrossAxisCount(
                        crossAxisCount: _calCrossAxisCount(),
                        crossAxisSpacing: 15,
                        mainAxisSpacing: 15,
                  ),
                  indicatorBuilder: (context, status) {
                    String msg = '';
                    switch (status) {
                      case IndicatorStatus.noMoreLoad:
                        msg = '';
                        break;
                      case IndicatorStatus.loadingMoreBusying:
                        msg = '加载中...';
                        break;
                      case IndicatorStatus.error:
                        msg = '加载失败，请稍后再试';
                        break;
                      case IndicatorStatus.empty:
                        msg = '暂无数据';
                        break;
                      default:
                        return const Center(child: LoadingIndicator());
                    }
                    return isNotBlank(msg)
                        ? Container(
                            padding: const EdgeInsets.all(15),
                            alignment: Alignment.center,
                            child: Text(
                              msg,
                              style: TextStyle(
                                color: customColors.weakTextColor,
                                fontSize: 14,
                              ),
                            ),
                          )
                        : const SizedBox();
                  },
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  int _calCrossAxisCount() {
    double width = ScreenUtil().screenWidth;
    if (width > CustomSize.maxWindowSize) {
      width = CustomSize.maxWindowSize;
    }

    return (width / 220).round();
  }


  void onItemDelete(BuildContext context, CreativeGallery item, int index) {
    showCustomTipsDialog(context, '是否删除作品', '删除后不可恢复，确定删除吗？', onSubmit: (diaContext) {

      EasyLoading.show(status: '删除中...');
      APIServer().deleteCreativeDrawItem('${item.id}').then((value) {
        EasyLoading.dismiss();
        // datasource.refresh(true);
        datasource.removeAt(index);
        setState(() {});
        diaContext.pop();
      }).catchError((e) {
        EasyLoading.dismiss();
        diaContext.pop();
      });
    });
  }
}
